//
//  HRGalleryView.swift
//  weiBo
//
//  Created by helong on 16/7/19.
//  Copyright © 2016年 helong. All rights reserved.
//

import UIKit
private let GalleryCellIdentifier = "GalleryCellIdentifier"
/// 选择要发送图片的视图
class HRGalleryView: UICollectionView {
    
    //  定义一个闭包把最后一个cell被选中的事件传递个控制器
    var addClosure: (() -> ())?
    
    //  初始化数据源数组
    var galleryArray = [UIImage]()
    
 
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: layout)
        //  设置代理
        self.dataSource = self
        self.delegate = self
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

     // MARK: - 设置UI
    private func setupUI(){
        // 注册cell
        registerClass(HRGalleryCell.self, forCellWithReuseIdentifier: GalleryCellIdentifier)
//        backgroundColor = randomColor()
        backgroundColor = UIColor.whiteColor()
        printLog()
        
        //  没有图片的时候隐藏
        hidden = true
    }
    
     // MARK: - 计算frame
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置cell的frame
        let itemWidth = (self.width - 2 * Margin) / 3
       let flowLayout = (collectionViewLayout as! UICollectionViewFlowLayout)
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumInteritemSpacing = Margin
        flowLayout.minimumLineSpacing = Margin
    }
    
    // MARK: - 保存选中的图片到数组中
    func addImage(image: UIImage){
        
        //  有配图就显示
        hidden = false
        galleryArray.append(image)
        reloadData()
    }
}

 // MARK: - UICollectionViewDataSource
extension HRGalleryView: UICollectionViewDataSource, UICollectionViewDelegate {
    
   
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //  如果只有0张,或者小于9张添加一张加号图
        if galleryArray.count > 0 && galleryArray.count < 9 {
            return galleryArray.count + 1
        }else {
        return galleryArray.count
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GalleryCellIdentifier, forIndexPath: indexPath) as! HRGalleryCell
        //  如果是最后一个cell不设置图片,作为判断依据
        if indexPath.item == galleryArray.count {
            cell.galleryImage = nil
        }else {
        cell.galleryImage = galleryArray[indexPath.item]
            cell.deleteClosure = {[weak self] in
                //  删除对应的cell
                self?.galleryArray.removeAtIndex(indexPath.item)
                //  如果数组中的数据没有了,就隐藏
                if self?.galleryArray.count == 0 {
                  self?.hidden = true
                }
                self?.reloadData()
            }
        }
        return cell
    }
    
     // MARK: - 选中最后一个cell执行添加图片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //  如果cell的indexpath是数组的最后一个
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        if indexPath.item == galleryArray.count {
            
            //  调用闭包
            addClosure?()
        }
    }
}



 // MARK: -  自定义cell
class HRGalleryCell: UICollectionViewCell {
    
    //  定义一个闭包把删除按钮点击事件传递给cell
    var deleteClosure: (() ->())?
    // 数据源
    var galleryImage:UIImage? {
        didSet{
            //  如果cell没有设置图片说面是最后的加号,然后给他设置图片和高亮效果
            if galleryImage == nil{
                pictureView.image = UIImage(named: "compose_pic_add")
                pictureView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                //  如果是加号cell  隐藏按钮
                closeButton.hidden = true
            }else {
                closeButton.hidden = false
                pictureView.image = galleryImage
                //  如果不是最后一张就不设置高亮图片
                pictureView.highlightedImage = nil
            }
        }
    }
    //  懒加载图片框
    private lazy var pictureView: UIImageView = UIImageView()
    //  懒加载按钮
    private lazy var closeButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        //  按钮绑定点击事件
        btn.addTarget(self, action: "deleteCell:", forControlEvents: .TouchUpInside)
        return btn
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     // MARK: - 删除按钮的点击事件
    @objc private func deleteCell(sender: UIButton){
        
        print("我被点击了")
        deleteClosure?()
    }
     // MARK: -  设置Cell 的UI
    private func setupUI(){
//        backgroundColor = randomColor()

        contentView.addSubview(pictureView)
        contentView.addSubview(closeButton)
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        closeButton.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.top.equalTo(contentView)
        }
    }
    
}